<template>
  <div class="login-page">
    <img src="/static/img/tuan.png" class="icon" mode="aspectFit">
    <button open-type="getUserInfo" class="login" @getuserinfo="bindgetuserinfo" @tab="canIUse">微信用户快速登陆</button>
  </div>
</template>

<script>
export default {
  name: '',
  data () {
    return {}
  },
  methods: {
    bindgetuserinfo (res) {
      var userInfo = res.mp.detail.userInfo
    
      if (userInfo) {
        this.setUser(userInfo)

        wx.showToast({
          title: '授权成功',
          icon: 'success',
        })

        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      }
    },
    async setUser (uInfo) {
      var that = this
      var user = {}
      var userInfo = wx.getStorageSync('userInfo')
      var openId = wx.getStorageSync('openId')

      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        if (userInfo && userInfo.name && userInfo.address && userInfo.mobile) {
          return
        }
      }
      
      user = await this.$request({
        url: '/GroupBuyBackendV1/getUserByOpenId/'+ openId
      })
      if (user && user.userId) {
        var info = await this.$request({
          url: '/GroupBuyBackendV1/user/'+ user.userId
        })
        if (info.name && info.address && info.mobile) {
          var userData = {
            name: info.name,
            mobile: info.mobile,
            address: info.address
          }
        } else {
          user = await this.$request({
            url: '/GroupBuyBackendV1/user',
            type: 'POST',
            data: {
              openId: openId,
              userInfo: JSON.stringify(uInfo),
              dateTime: new Date().getTime()
            }
          })
        }
      } else {
        user = await this.$request({
          url: '/GroupBuyBackendV1/user',
          type: 'POST',
          data: {
            openId: openId,
            userInfo: JSON.stringify(uInfo),
            dateTime: new Date().getTime()
          }
        })
      }
      if (user.userId) {
        wx.setStorageSync('userId', user.userId)
        wx.setStorageSync('userIcon', uInfo.avatarUrl)
        wx.setStorageSync('userJson', JSON.stringify(uInfo))
      }
     
      if (typeof userData != 'undefined') {
        wx.setStorageSync('userInfo', JSON.stringify(userData))
      }
    },
    canIUse (res) {
      if (!wx.canIUse('button.open-type.getUserInfo')) {
        wx.showModal({
          content: '请升级您的微信'
        })
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  .login-page {
    margin: 0 40rpx
    padding-top: 160rpx
    .icon {
      width: 128rpx
      height: 128rpx
      margin: 0 auto
    }
    .login {
      color: #fff
      font-size: 32rpx
      background: #F40009
      line-height: 80rpx
      margin-top: 300rpx
      box-sizing: border-box
    }
  }

</style>
